//
//  Utils.m
//  AppFinance
//
//  Created by wei on 12-4-11.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AFUtils.h"

#import <CommonCrypto/CommonDigest.h>

static int _currentResolution = -1;

@implementation AFUtils

////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - 时间

+ (NSString *) unixTime:(NSString*) unixTime format:(NSString*) format{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:date];
}


+ (NSString *) unixTime:(NSString*) unixTime{
    
    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    //NSDate *date = [NSDate date];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
    
    //NSInteger year = [dateComponents year];
    //NSInteger month = [dateComponents month];
    //NSInteger day = [dateComponents day];
    NSInteger hour = [dateComponents hour];
    NSInteger minute = [dateComponents minute];
    
    NSString *h = nil;
    NSString *m = nil;
    if (hour < 10) {
        h = [NSString stringWithFormat:@"0%i",(int)hour];
    } else {
        h = [NSString stringWithFormat:@"%i",(int)hour];
    }
    
    if (minute < 10) {
        m = [NSString stringWithFormat:@"0%i",(int)minute];
    } else {
        m = [NSString stringWithFormat:@"%i",(int)minute];
    }
    
    return [NSString stringWithFormat:@"%@:%@",h,m];
}



/**
 *  GetWeekForDate
 *  根据日期获取星期
 *
 *  @param NSString strDate 日期(yyyy-MM-dd)
 *
 *  @return NSString / empty
 */
+(NSString*) GetWeekForDate:(NSString *) strDate{
    
    if (![strDate isEqualToString:@""]) {
        
        //时间格式化
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        //获取对应时间
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *cdate = [formatter dateFromString:strDate];
        
        //获取时间信息
        [formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"];
        NSString *locationString=[formatter stringFromDate: cdate];
        
        NSArray *arrDate = [locationString componentsSeparatedByString:@" "];
        NSString *strWeek = [NSString stringWithFormat:@"%@",[arrDate objectAtIndex:1]];
        
        if ([strWeek isEqualToString:@"Sunday"])        return @"星期日";
        else if ([strWeek isEqualToString:@"Monday"])   return @"星期一";
        else if ([strWeek isEqualToString:@"Tuesday"])  return @"星期二";
        else if ([strWeek isEqualToString:@"Wednesday"])return @"星期三";
        else if ([strWeek isEqualToString:@"Thursday"]) return @"星期四";
        else if ([strWeek isEqualToString:@"Friday"])   return @"星期五";
        else if ([strWeek isEqualToString:@"Saturday"]) return @"星期六";
        else return strWeek;
    }else return @"";
}




+ (int) unixTimeMinute:(NSString*) unixTime{
    
    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    //NSDate *date = [NSDate date];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
    
    //NSInteger hour = [dateComponents hour];
    NSInteger minute = [dateComponents minute];
    return (int)minute;
}

+ (NSString *) unixTimeHand:(NSString*) unixTime{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm:ss"];
    return [dateFormatter stringFromDate:date];
}

+ (NSString *) unixTimePoint:(NSString*) unixTime{
    
    //NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    //NSDate *date = [NSDate date];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    
    /*NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
    NSInteger year = [dateComponents year];
    NSInteger month = [dateComponents month];
    NSInteger day = [dateComponents day];
    //NSInteger hour = [dateComponents hour];
    //NSInteger minute = [dateComponents minute];
    //NSInteger second = [dateComponents second];
    */
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setDateFormat:@"yyMMdd"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    //return [NSString stringWithFormat:@"%i%i%i",year,month,day];
    return [dateFormatter stringFromDate:date];
}

+ (NSString *) unixTimePointMin:(NSString*) unixTime{
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 日时分
    [dateFormatter setDateFormat:@"ddHHmm"];
    //return [NSString stringWithFormat:@"%i%i%i",year,month,day];
    return [dateFormatter stringFromDate:date];
}

+ (NSString *) unixTimePointYYYYMMDDHHMM:(NSString*) unixTime{
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: [unixTime intValue]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 日时分
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //return [NSString stringWithFormat:@"%i%i%i",year,month,day];
    return [dateFormatter stringFromDate:date];
}

+ (NSString*) stringToDate:(NSString *)_time withFormat:(NSString *)format{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

   [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date = [formatter dateFromString:_time];

    [formatter setDateFormat:format];

    return [formatter stringFromDate:date];
}


+ (NSString*) stringToDate:(NSString *)_time{
    
    //Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec 
    //_time = [_time stringByReplacingOccurrencesOfString:@"+0800" withString:@"+0000"];
    if ([_time rangeOfString:@"Jan"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Jan" withString:@"01"];
    } else if ([_time rangeOfString:@"Feb"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Feb" withString:@"02"];
    } else if ([_time rangeOfString:@"Mar"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Mar" withString:@"03"];
    } else if ([_time rangeOfString:@"Apr"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Apr" withString:@"04"];
    } else if ([_time rangeOfString:@"May"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"May" withString:@"05"];
    } else if ([_time rangeOfString:@"Jun"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Jun" withString:@"06"];
    } else if ([_time rangeOfString:@"Jul"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Jul" withString:@"07"];
    } else if ([_time rangeOfString:@"Aug"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Aug" withString:@"08"];
    } else if ([_time rangeOfString:@"Sep"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Sep" withString:@"09"];
    } else if ([_time rangeOfString:@"Oct"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Oct" withString:@"10"];
    } else if ([_time rangeOfString:@"Nov"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Nov" withString:@"11"];
    } else if ([_time rangeOfString:@"Dec"].length > 0) {
        _time = [_time stringByReplacingOccurrencesOfString:@"Dec" withString:@"12"];
    }

    // ios 手机上 格式化 有 字符串的(如：Wed、May) 日期失败
    //Wed, 20 Jun 2012 21:53:33 +0800
    // 去掉 星期
    _time = [_time substringFromIndex:5];
    // NSLog(@"  _time 2 = %@",_time);
    
    //NSString *time = @"Sat, 26 May 2012 08:26:00 +0800";
    
    NSDateFormatter* df = nil;
    df = [[NSDateFormatter alloc] init];
    //[df setTimeStyle:NSDateFormatterFullStyle];
    //[df setFormatterBehavior:NSDateFormatterBehavior10_4];
    [df setDateFormat:@"d LL yyyy HH:mm:ss Z"];
    //[df setDateFormat:@"EEE, d LLL Y H:m:s Z"];
    
    NSDate *convertedDate = [df dateFromString:_time];     
    /*
    NSLog(@"  NSdate = %@",convertedDate);
    NSDateFormatter *df3 = [[NSDateFormatter alloc] init];
    //[df3 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    //NSLog(@"DATE FORMAT:%@", [df3 dateFromString:@"2008-12-29T00:27:42-0800"]);
    [df3 setDateFormat:@"EEE, d LL yyyy HH:mm:ss"];
    NSLog(@"DATE FORMAT 3: %@", [df3 dateFromString:@"Wed, 20 06 2012 23:08:00"]);
    */
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    return [dateFormatter stringFromDate:convertedDate];
}


+(int)nowMinute{
    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    //NSDate *date = [NSDate date];
    NSDate *date = [NSDate date];
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
    
    NSInteger minute = [dateComponents minute];
    
    return minute;
}

+(NSString *)nowDataChangeMinToUnixTime:(int)_min{
    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    //NSDate *date = [NSDate date];
    NSDate *date = [NSDate date];
    NSLog(@" date 1 = %@",date);
    
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
    
    //NSInteger minute = [dateComponents minute];
    [dateComponents setMinute:_min];
    
    NSDate *_date2 = [dateComponents date];
    NSLog(@" date 2 = %@",date);
    double _doubleDate = [_date2 timeIntervalSince1970];
    return [NSString stringWithFormat:@"%.0f", _doubleDate];
}

+ (NSString *) dateStringAForNow{
    NSDate *date = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    // 小写的"hh"，那么时间将会跟着系统设置变成12小时或者24小时制。大写的"HH"，则强制为24小时制
    [df setDateFormat:@"MM-dd HH:mm"];
    return [df stringFromDate:date];
}

+(long long int)localUnixTime{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    long long int unixTime = (long long int)time;
    return unixTime;
}

// 2015-01-19 18:01:02  YYYY-MM-dd HH:mm:ss
// 2015/1/19 18:01:02  YYYY/MM/dd HH:mm:ss
+ (NSString *) dateStringNowForFormat:(NSString*)_format{
    NSDate *date = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    // 小写的"hh"，那么时间将会跟着系统设置变成12小时或者24小时制。大写的"HH"，则强制为24小时制
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [df stringFromDate:date];
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - UIDevice
////////////////////////////////////////////////////////////////////////////////
+ (UIDeviceResolution) currentResolution {
    
    if (_currentResolution > 0) {
        return _currentResolution;
    }
    
    //if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    //    NSLog(@" UIUserInterfaceIdiomPhone ");
    //} else {
    //    NSLog(@" UIUserInterfaceIdiomPad ");
    //}
    //CGSize size =  [[UIScreen mainScreen] currentMode].size;
    //NSLog(@" size w = %f, h = %F", size.width, size.height);
    //CGSize bounds = [[UIScreen mainScreen] bounds].size;
    //NSLog(@" bounds size w = %f, h = %f", bounds.width, bounds.height);
    //NSLog(@" [UIScreen mainScreen].scale= %f", [UIScreen mainScreen].scale);
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)]) {
            //NSLog(@" [[UIScreen mainScreen] respondsToSelector: @selector(scale)]  == YES");
            
            CGSize result = [[UIScreen mainScreen] bounds].size;
            result = CGSizeMake(result.width * [UIScreen mainScreen].scale, result.height * [UIScreen mainScreen].scale);
            
            if (result.height == 480) {
                _currentResolution = UIDevice_iPhone3;
            } else if(result.height == 960 ){
                _currentResolution = UIDevice_iPhone4;
            } else {
                _currentResolution = UIDevice_iPhone5;
            }
        } else{
            _currentResolution = UIDevice_iPhone3;
        }
    } else{
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)]) {
            _currentResolution = UIDevice_iPad3;
        } else {
            _currentResolution = UIDevice_iPad2;
        }
    }
    
    return _currentResolution;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - MD5
////////////////////////////////////////////////////////////////////////////////
+(NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}




// -------- test ---------
// "yyyy-MM-dd hh:mm:ss" //12小时制
// "yyyy-MM-dd HH:mm:ss" //24小时制
-(void)test{
    
    // 获取 unix time
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    long long int date4 = (long long int)time;
    NSLog(@" date4 = %lld", date4);
    
    
    NSDate *date = [NSDate date];
    NSLog(@" date 1 = %@", date); // 直接打印 为 GTM + 0 时间
    
    // date to string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *lodate = [dateFormatter stringFromDate:date];  // 格式化之后为 本地时间
    NSLog(@" localDate 2 = %@", lodate);
    
    // string to date
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *new_date = [formatter dateFromString:lodate];
    NSLog(@" new_date = %@", new_date);
    
    
    
     NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSChineseCalendar];
     //        NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];//这是用来输出时区名称的
     //        for (int i = 0; i < [timeZoneNames count]; i++) {
     //            NSLog(@" timeZoneNames i = %@", [timeZoneNames objectAtIndex:i]);
     //        }
     //        NSLog(@"timeZoneNames is %@", timeZoneNames);
     NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];//中国时间
     [calendar setTimeZone:timeZone];
    
     NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
     NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date]];
     
     int hour = [dateComponents hour];
    
     NSLog(@" hour = %i", hour);
}

////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - 颜色

// 这里的 RGB 为 【mac 软件 数码测试计】显示的原生值
+ (UIColor *) UIColorFromRed:(float) red green:(float) green blue:(float) blue  {
    float r = red/255.0;
    float g = green/255.0 ;
    float b = blue/255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:1.0];
}

+ (UIColor *) UIColorFromRGB:(int) rgbValue alpha:(float) alphaValue {
    float r = ((float)((rgbValue & 0xFF0000) >> 16))/255.0;
    float g = ((float)((rgbValue & 0xFF00) >> 8))/255.0 ;
    float b = ((float)(rgbValue & 0xFF))/255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:alphaValue];
}


+ (void) alertMessage:(NSString *) inmsg{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"信息"
                                                        message:inmsg
                                                       delegate:nil
                                              cancelButtonTitle:@"好"
                                              otherButtonTitles:nil, nil];
    
    [alertView show];
}

+(void)alertMessageNoButton:(NSString *) inmsg{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"信息"
                                                        message:inmsg
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:nil, nil];
    
    [alertView show];
   
   [self performSelector:@selector(dimissAlert:) withObject:alertView afterDelay:0.8];
}



+(void)dimissAlert:(UIAlertView * )alertView{
    if(alertView){

    [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES];
    }
}


@end
